﻿using Abp.Domain.Repositories;
using RMM.Core.Entity.Massagistes;
using RMM.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity.SqlServer;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RMM.Core.Massagistes
{
    public class MassagistService : EntityDomainService<Massagist, long>, IMassagistService
    {
        private readonly IRepository<Massagist, long> _massagistRepository;
        private readonly IRepository<MassagistExtend, long> _massagistExtendRepository;
        private readonly IRepository<MassagistShare, long> _massagistShareRepository;
        private readonly IRepository<MassagistProject, long> _massagistProjectRepository;

        public MassagistService(IRepository<Massagist, long> Repository
            , IRepository<MassagistExtend, long> massagistExtendRepository
            , IRepository<MassagistShare, long> massagistShareRepository
            , IRepository<MassagistProject, long> massagistProjectRepository)
            : base(Repository)
        {
            _massagistExtendRepository = massagistExtendRepository;
            _massagistRepository = Repository;
            _massagistShareRepository = massagistShareRepository;
            _massagistProjectRepository = massagistProjectRepository;
        }



        public async Task<List<Massagist>> GetFreeMassagistAsync(int shopId, DateTime StartTime, DateTime EndTime)
        {
            //所有技师
            var massagistList = _massagistRepository.GetAll()
                .Where(p => p.ShopId == shopId).Select(p=>p.Id).ToList();
            //没时间的技师
            var massagistExtendList = _massagistExtendRepository.GetAll()
                .Where(p =>!(
                (SqlFunctions.DateDiff("mi", StartTime, p.StartTime).Value >= 0 && SqlFunctions.DateDiff("mi", EndTime, p.StartTime).Value >= 0) ||
                (SqlFunctions.DateDiff("mi", p.EndTime, StartTime).Value >= 0))).ToList();
            //所有共享技师
            var shardMassagiust = _massagistShareRepository.GetAll()
                .Where(p => p.ShopId == shopId)
                .Select(p => p.MassagistId)
                .ToList();

            //差集就是有时间的技师
            massagistList.AddRange(shardMassagiust);
            var idList = massagistList.Distinct().Except(massagistExtendList.Select(p => p.MassagistId));

            var list = await _massagistRepository.GetAllListAsync(p => idList.Contains(p.Id));
            return list;
        }

        public Task<IQueryable<MassagistShare>> GetShareMassagistListAsync()
        {
            return Task.FromResult(_massagistShareRepository.GetAll());
        }

        public Task<IQueryable<MassagistProject>> GetMassagistProjectAsync()
        {
            return Task.FromResult(_massagistProjectRepository.GetAll());
        }

        public IRepository<MassagistProject, long> GetMassagistProjectRepository() => _massagistProjectRepository;
        
    }
}
